package com.Lixiaoqian.Gulangyu.net

import com.Lixiaoqian.Gulangyu.base.QianTechApp
import com.Lixiaoqian.Gulangyu.utils.LogUtils
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Converter
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

/**
 * api访问
 * Created by huangzhibo on 2018-03-01.
 * mail:1043202454@qq.com
 */
class ApiManager private constructor() {
    private var factory: Converter.Factory= GsonConverterFactory.create()
    private lateinit var retrofit: Retrofit
    lateinit var okHttpClient: OkHttpClient

    init {
        initOKhttp()
    }

    /**
     * 初始化
     */
    private fun initOKhttp() {
        val loggingInterceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
            override fun log(message: String?) {
                LogUtils.w("retrofit$message")
            }
        })
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        val builder = OkHttpClient.Builder()
        builder.addInterceptor(loggingInterceptor)
        //OkhttpClient设置
        val cache = Cache(File(QianTechApp.context.cacheDir, "File_Kotlin"), 14 * 1024 * 100)
        builder.cache(cache)
        builder.connectTimeout(8, TimeUnit.SECONDS)
        builder.readTimeout(5, TimeUnit.SECONDS)
        builder.writeTimeout(5, TimeUnit.SECONDS)
        okHttpClient = builder.build()
    }

    fun buildRetrofit():ApiManager {
        retrofit = Retrofit.Builder().client(okHttpClient)
                .addConverterFactory(factory)
                .baseUrl(ApiConstant.API_BASE_URL)
                .build()
        return this
    }

    companion object {
        fun getInstance(): ApiManager {
            return Inner.apiManager
        }
    }

    private object Inner {
        val apiManager = ApiManager()
    }

    /**
     *设置数据转化器
     * @factory
     */
    fun setConverterFactory(factory: Converter.Factory ): ApiManager {
        this.factory = factory
        return this
    }

    /**
     * api接口类导入
     */
    fun <T> createRequestClass(reqService: Class<T>): T {
        return retrofit.create(reqService)
    }

}